package com.zyfdroid.mindnote2;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.preference.*;
import android.text.TextUtils;
import android.widget.Toast;
import android.os.Bundle;
import androidx.documentfile.provider.DocumentFile;
import com.zyfdroid.mindnote2.utils.AppSettings;
import com.zyfdroid.mindnote2.utils.DocumentManager;
import com.zyfdroid.mindnote2.utils.RunUtils;
import com.zyfdroid.mindnote2.utils.ShareFileProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BackupActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean transparent = AppSettings.transparentWindow;
        if (transparent) {
            setTheme(R.style.Theme_思维笔记_Transparent);
        }
        addPreferencesFromResource(R.xml.backup);
        if (getActionBar() != null) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);
        }

        initPreference();

    }

    Preference backupPathText = null;

    private void initPreference() {
        PreferenceManager pm = getPreferenceManager();
        backupPathText = pm.findPreference("backupPath");
        if (!TextUtils.isEmpty(AppSettings.backupContentUri)) {
            backupPathText.setSummary(AppSettings.backupContentUri);
        } else {
            backupPathText.setSummary("<无>");
        }

        pm.findPreference("selectBackupPath").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE),ACTION_SELECTBACKUPPATH);
                return true;
            }
        });

        pm.findPreference("doBackup").setOnPreferenceClickListener(this::doBackup);
        if(AppSettings.lastBackupTime > 0){
            pm.findPreference("doBackup").setSummary("上次备份："+DocumentManager.dateFormat.format(new Date(AppSettings.lastBackupTime)));
        }
        pm.findPreference("doRestore").setOnPreferenceClickListener(this::doRestore);
        pm.findPreference("doExport").setOnPreferenceClickListener(this::doExport);
    }


    private static final int ACTION_SELECTBACKUPPATH = 21;
    private static final int ACTION_SELECTRESTOREPATH = 139;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ACTION_SELECTBACKUPPATH){
            if(resultCode == RESULT_OK){
                if(data != null){
                    Uri uri = data.getData();
                    if (uri != null) {
                        // 保存获取的目录权限
                        final int takeFlags = data.getFlags()
                                & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        getContentResolver().takePersistableUriPermission(uri,  takeFlags);
                        // 保存uri
                        AppSettings.backupContentUri = uri.toString();
                        backupPathText.setSummary(uri.toString());
                        AppSettings.saveSettings(this);

                    }
                }
            }
        }
        if(requestCode == ACTION_SELECTRESTOREPATH){
            if(resultCode == RESULT_OK){
                if(data != null){
                    doRestoreAfterSelect(data.getData());
                }
            }
        }
    }
    private void doRestoreAfterSelect(Uri result) {
        if(result == null){
            return;
        }
        final ProgressDialog progressDialog = ProgressDialog.show(this,null,"正在恢复...",true);
        progressDialog.setCancelable(false);
        Handler hWnd = new Handler();
        new Thread(() -> {
            try {
                DocumentManager.restoreFile(this,this.getContentResolver().openInputStream(result));
                hWnd.post(()-> Toast.makeText(this, "恢复备份成功",Toast.LENGTH_SHORT).show());
            } catch (IOException e) {
                e.printStackTrace();
                hWnd.post(()-> Toast.makeText(this, "恢复失败："+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
            }
            hWnd.post(progressDialog::dismiss);
        }).start();
    }

    private boolean doExport(Preference preference) {
        BackupActivity.doExport(this);
        return true;
    }

    private boolean doBackup(Preference preference) {
        final ProgressDialog progressDialog = ProgressDialog.show(this,null,"正在备份...",true);
        progressDialog.setCancelable(false);
        new RunUtils.Promise<Void>(()->{
            String uriStr = AppSettings.backupContentUri;
            if(TextUtils.isEmpty(uriStr)){
                throw new NoSuchFieldException("");
            }
            String backupFilePath = DocumentManager.backupAll(this);
            Uri backupDirUri = Uri.parse(uriStr);
            DocumentFile backupDir = DocumentFile.fromTreeUri(this,backupDirUri);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            DocumentFile file = backupDir.createFile("application/zip","mindnote_backup_"+sdf.format(new Date()));
            try(FileInputStream fis = new FileInputStream(backupFilePath)) {
                try (OutputStream os = this.getContentResolver().openOutputStream(file.getUri())) {
                    byte[] data = new byte[2048];
                    int len = 0;
                    while ((len = fis.read(data))> 0){
                        os.write(data,0,len);
                    }
                    os.flush();
                }
            }
            return null;
        }).then((unused -> {
            AppSettings.lastBackupTime = System.currentTimeMillis();
            AppSettings.saveSettings(this);
            Toast.makeText(this, "备份完成", Toast.LENGTH_SHORT).show();
            getPreferenceManager().findPreference("doBackup").setSummary("上次备份：现在");
            getPreferenceManager().findPreference("doBackup").setEnabled(false);
            progressDialog.dismiss();
        })).Catch((err)->{
            if(err instanceof NoSuchFieldException){
                Toast.makeText(this, "未选择备份路径", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "备份失败:"+err.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
            progressDialog.dismiss();
        });
        return true;
    }

    private boolean doRestore(Preference preference) {
        new AlertDialog.Builder(this).setTitle("是否恢复备份？").setMessage("是否恢复备份？一些笔记可能会被覆盖")
                .setNegativeButton(android.R.string.no,null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                        i.setType("application/zip");
                        startActivityForResult(i,ACTION_SELECTRESTOREPATH);
                    }
                }).create().show();
        return true;
    }

    @Override
    public boolean onNavigateUp() {
        finish();
        return super.onNavigateUp();
    }
    /*

    public static class BackupPreferenceFragment extends PreferenceFragment {

        ActivityResultLauncher<Void> selectBackupPathLauncher = null;
        ActivityResultLauncher<String> selectRestoreFileLauncher = null;


        @Override
        @SuppressLint("WrongConstant")
        public void onCreatePreferences(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState, @Nullable @org.jetbrains.annotations.Nullable String rootKey) {




            selectRestoreFileLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), this::doRestoreAfterSelect);
        }

        
        private boolean selectPath(Preference preference) {
            selectBackupPathLauncher.launch(null);
            return true;
        }





    }
*/
    static void doExport(Context ctx) {
        final ProgressDialog progressDialog = ProgressDialog.show(ctx, null, "正在导出...", true);
        progressDialog.setCancelable(false);
        Handler hWnd = new Handler();
        new Thread(() -> {
            try {
                String path = DocumentManager.backupAll(ctx);
                hWnd.post(() -> {
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    Uri uri = ShareFileProvider.getUriForFile(ctx, ctx.getPackageName(), new File(path));
                    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                    shareIntent.setDataAndType(uri, "application/zip");
                    shareIntent.setClipData(ClipData.newRawUri("", uri));
                    shareIntent.addFlags(
                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    ctx.startActivity(Intent.createChooser(shareIntent, "发送备份"));
                });
            } catch (IOException e) {
                e.printStackTrace();
                hWnd.post(() -> Toast.makeText(ctx, "导出失败：" + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show());
            }

            hWnd.post(progressDialog::dismiss);
        }).start();
    }
}